package com.example.utils;

import io.jsonwebtoken.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import java.security.Key;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by alading-qs on 2016/12/29.
 * token生成类
 */
public class JwtUtil {

    private static Logger logger = LoggerFactory.getLogger(JwtUtil.class);

    private static final SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    /**
     * 生成token
     * @param id
     * @param issuer
     * @param subject
     * @param ttlMillis
     * @param key
     * @return
     */
    public static String createToken(String id, String issuer, String subject, long ttlMillis, String key) {

        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS512;

        logger.trace("Signature algorithm {}", signatureAlgorithm.getValue());

        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);

        byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(key);
        Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());

        JwtBuilder builder = Jwts.builder().setId(id)
                .setIssuedAt(now)
                .setSubject(subject)
                .setIssuer(issuer)
                .signWith(signatureAlgorithm, signingKey);

        if (ttlMillis >= 0) {
            long expMillis = nowMillis + ttlMillis;
            Date exp = new Date(expMillis);
            System.out.println(sf.format(exp));
            builder.setExpiration(exp);
        }
        return builder.compact();
    }

    /**
     * 生成token
     * @param id
     * @param issuer
     * @param subject
     * @param key
     * @return
     */
    public static String createToken(String id, String issuer, String subject,String key) {
        return createToken(id, issuer, subject, 0, key);
    }

    /**
     * 验证token
     * @param token
     * @param key
     * @return
     */
    public static Jws verifyToken(String token, String key) {
        Jws jws = null;
        try {
            jws = Jwts.parser().setSigningKey(DatatypeConverter.parseBase64Binary(key)).parseClaimsJws(token);
            logger.trace("Jws:{}", jws);
        } catch (SignatureException e) {
            logger.error("token verification failed",e);
        }
        return jws;
    }
}
